//
//  EPCodeView.swift
//  EPHome
//
//  Created by liujianlong on 2022/8/30.
//

import UIKit

class EPCodeView: UIView {
    var gap:CGFloat = 10
    var itemTextcolor:UIColor = .black
    var itemBackgroundColor:UIColor = "#EEEEEE".color()
    var itemRadius:CGFloat = 4
    private var oldText:(Int,String) = (0,"")
    var num:Int = 0 {
        didSet{
            for input in self.subviews{
                if input.tag != 300{
                    input.removeFromSuperview()
                }
            }
            let w = (self.frame.width - gap * CGFloat(num - 1)) / CGFloat(num)
            for i in 0..<num{
                let view = EPCodeTextField()
                view.textColor = self.itemTextcolor
                view.backgroundColor = self.itemBackgroundColor
                view.cornerRadius = self.itemRadius
                view.delegate = self
                view.keyboardType = .numberPad
                view.tag = 200 + i
                self.addSubview(view)
                view.snp.makeConstraints { make in
                    make.top.bottom.equalToSuperview()
                    make.width.equalTo(w)
                    make.left.equalToSuperview().offset((w + gap) * CGFloat(i))
                }
            }
        }
    }
}

//MARK: - UITextFieldDelegate
extension EPCodeView:UITextFieldDelegate{
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField.text!.count > 0 && textField.tag < 300 {
            self.oldText = (Int(textField.tag),textField.text!)
        }
        textField.text = ""
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        if textField.text!.count == 0 && self.oldText.0 == textField.tag{
            textField.text = self.oldText.1
        }
        return true
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
        if string.isNumber() == false && string != ""{return false}
        if textField.text!.count >= 1 && string != ""{return false}
        
        ///删除键，
        if string == ""{
            if textField.tag > 200{
                self.oldText = (0,"")///清除记录的
                ///拿到前一个输入框，删除此输入框并且切换成第一响应者
                let last = self.viewWithTag(textField.tag - 1) as! EPCodeTextField
                last.text = ""
                last.becomeFirstResponder()
            }
            return true
        }
        else{
            ///当前输入框赋值后
            textField.text = string
            textField.endEditing(true)
            ///自动把下一个输入框切换成第一响应者
            var index = textField.tag
            while index >= 200 && index < 200 + self.num{
                ///获取下一个输入框
                let next = self.viewWithTag(index + 1) as? EPCodeTextField ?? nil
                if next != nil{
                    if next!.text!.count <= 0{
                        ///切换成第一响应者
                        next?.becomeFirstResponder()
                        break
                    }else{
                        ///如果下个输入框有值了，则继续递进下一个输入框成为第一响应者
                        index += 1
                    }
                }
                break
            }
            return true
        }
        
    }
    
}


class EPCodeTextField: UITextField {
    ///文本位置居中
    override func textRect(forBounds bounds: CGRect) -> CGRect {
        let w = bounds.width
        return CGRect(origin: CGPoint(x: w / 2 - 4, y: 0), size: bounds.size)
    }
    ///光标的位置居中
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        let w = bounds.width
        return CGRect(origin: CGPoint(x: w / 2, y: 0), size: bounds.size)
    }
    ///输入框没有内容，删除按钮也有效
    override func deleteBackward() {
        _ = self.delegate?.textField?(self, shouldChangeCharactersIn:NSRange(location:0, length:0), replacementString: "")
    }
    
}
